package com.doudou.dubbo.demo;

import com.doudou.dubbo.demo.api.GreetingService;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.RpcContext;

/**
 * @author zhaozw
 * @version 1.0
 * @date 2025-07-22 19:11
 **/
public class ApiAsyncConsumerForCompletableFuture2 {

    public static void main(String[] args) throws InterruptedException {
        // 创建服务引用对象，并设置数据
        ReferenceConfig<GreetingService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer"));
        referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
        referenceConfig.setInterface(GreetingService.class);
        referenceConfig.setTimeout(3000);
        referenceConfig.setVersion("1.0.0");
        referenceConfig.setGroup("dubbo");

        // 设置异步
        referenceConfig.setAsync(true);

        // 调用方法
        GreetingService greetingService = referenceConfig.get();
        RpcContext.getContext().setAttachment("company", "juzi");
        String result = greetingService.sayHello("world");
        System.out.println("result >>> " + result);

        // 异步执行回调
        CompletableFuture<Object> completableFuture = RpcContext.getContext()
                .getCompletableFuture();
        completableFuture.whenComplete((v, t) -> {
            if (Objects.nonNull(t)) {
                t.printStackTrace();
            } else {
                System.out.println(v);
            }
        });
        System.out.println("over");
        Thread.currentThread().join();
    }
}
